package com.lyf.boot.core.server;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import lombok.Data;

import java.lang.management.ManagementFactory;
import java.util.Date;

/**
 * @author Luyufan
 * @date 2024/1/11 16:07
 **/
@Data
public class Jvm {

    /**
     * 当前JVM占用的内存总数(M)
     */
    private double total;

    /**
     * JVM最大可用内存总数(M)
     */
    private double max;

    /**
     * JVM空闲内存(M)
     */
    private double free;

    /**
     * JDK版本
     */
    private String version;

    /**
     * JDK路径
     */
    private String home;

    /**
     * 获取JDK名称
     */
    public String getName(){
        return ManagementFactory.getRuntimeMXBean().getVmName();
    }

    /**
     * JDK启动时间
     */
    public String getStartTime(){
        long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        return DateUtil.format(new Date(startTime), DatePattern.NORM_DATETIME_PATTERN);
    }

    /**
     * JDK运行时间
     */
    public String getRunTime(){
        long startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        return timeDistance(new Date(), new Date(startTime));
    }

    /**
     * 运行参数
     */
    public String getInputArgs(){
        return ManagementFactory.getRuntimeMXBean().getInputArguments().toString();
    }

    private String timeDistance(Date endDate, Date startTime){
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
}
